package service;

import dataAcsessObject.Exception.NotEntityFoundException;
import dataAcsessObject.JPADAOFactory;
import entity.User;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import service.exception.ObjectNotFoundException;
import valueObject.UserVO;

/**
 *
 * @author Juan Hernández Serrato
 */
public class UserService extends AbstractService<UserVO, User> {

    @Override
    public void create(UserVO valueObject, EntityManager em) {
        User user = valueObject.toEntity();
        JPADAOFactory.getInstance().getUserDAO().create(user, em);
    }

    @Override
    public void update(UserVO valueObject, EntityManager em) throws ObjectNotFoundException {
        try {
            User user = JPADAOFactory.getInstance().getUserDAO().findById(valueObject.getUsername(), em);
            user = valueObject.toEntity();
            JPADAOFactory.getInstance().getUserDAO().update(user, em);
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public void delete(Object id, EntityManager em) throws ObjectNotFoundException {
        try {
            User user = JPADAOFactory.getInstance().getUserDAO().findById(id, em);
            JPADAOFactory.getInstance().getUserDAO().delete(user, em);
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public UserVO findById(Object id, EntityManager em) throws ObjectNotFoundException {
        try { 
            User user = JPADAOFactory.getInstance().getUserDAO().findById(id, em);
            UserVO vo = user.toValueObject();
            return vo;
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public List<UserVO> findAll(EntityManager em) {
        List<UserVO> usersVO = new ArrayList<UserVO>();
        List<User> users = JPADAOFactory.getInstance().getUserDAO().findAll(em);
        for (User user : users) {
            usersVO.add(user.toValueObject());
        }
        return usersVO;
    }

    @Override
    public List<UserVO> findRange(int begin, int end, EntityManager em) {
        List<UserVO> usersVO = new ArrayList<UserVO>();
        List<User> users = JPADAOFactory.getInstance().getUserDAO().findRange(begin, end, em);
        for (User user : users) {
            usersVO.add(user.toValueObject());
        }
        return usersVO;
    }

}
